package HttpClient

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/FileName"
	"io"
	"net/http"
	"os"
)

func TestUrlFileCanBeOpen(url string) error {
	// 创建HTTP请求
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("bad status: %s", resp.Status)
	}

	return nil
}

func DownloadFile(url string, filePath string, fileName string) error {
	// 创建HTTP请求
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("bad status: %s", resp.Status)
	}

	localFile := FileName.GetOsFilePath(filePath + "/" + fileName)

	// 创建多级目录
	os.MkdirAll(FileName.GetOsFilePath(filePath), os.ModePerm)

	// 创建文件
	out, err := os.Create(localFile)
	if err != nil {
		return err
	}
	defer out.Close()

	// 将响应体写入文件
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return err
	}

	return nil
}
